<template>
  <el-dropdown @command="handleExport" trigger="click">
    <el-button type="success" :loading="exporting">
      <el-icon><Download /></el-icon>
      导出数据
      <el-icon class="el-icon--right"><ArrowDown /></el-icon>
    </el-button>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item command="csv">
          <el-icon><Document /></el-icon>
          导出为CSV
        </el-dropdown-item>
        <el-dropdown-item command="json">
          <el-icon><Document /></el-icon>
          导出为JSON
        </el-dropdown-item>
        <el-dropdown-item command="excel" disabled>
          <el-icon><Document /></el-icon>
          导出为Excel
          <el-tag size="small" type="info">需安装xlsx</el-tag>
        </el-dropdown-item>
        <el-dropdown-item command="pdf" disabled>
          <el-icon><Document /></el-icon>
          导出为PDF
          <el-tag size="small" type="info">需安装jsPDF</el-tag>
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { exportToCSV, exportToJSON, formatExportData } from '@/utils/export'

const props = defineProps({
  // 要导出的数据
  data: {
    type: Array,
    required: true,
    default: () => []
  },
  // 列配置
  columns: {
    type: Array,
    required: true,
    default: () => []
  },
  // 文件名前缀
  filename: {
    type: String,
    default: 'export'
  },
  // 数据类型（用于获取默认列配置）
  dataType: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['export'])

const exporting = ref(false)

const handleExport = async (command) => {
  if (!props.data || props.data.length === 0) {
    ElMessage.warning('没有数据可导出')
    return
  }

  exporting.value = true

  try {
    // 格式化数据
    const formattedData = formatExportData(props.data, props.columns)
    
    // 生成文件名
    const timestamp = new Date().toISOString().slice(0, 10)
    const filename = `${props.filename}_${timestamp}`
    
    switch (command) {
      case 'csv':
        exportToCSV(formattedData, props.columns, `${filename}.csv`)
        ElMessage.success('CSV文件导出成功')
        break
        
      case 'json':
        exportToJSON(formattedData, `${filename}.json`)
        ElMessage.success('JSON文件导出成功')
        break
        
      case 'excel':
        ElMessage.info('Excel导出功能需要安装xlsx库')
        break
        
      case 'pdf':
        ElMessage.info('PDF导出功能需要安装jsPDF库')
        break
        
      default:
        ElMessage.error('不支持的导出格式')
    }
    
    // 触发导出事件
    emit('export', {
      format: command,
      data: formattedData,
      filename: filename
    })
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  } finally {
    exporting.value = false
  }
}
</script>

<style scoped>
.el-dropdown-menu .el-dropdown-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.el-tag {
  margin-left: auto;
}
</style>
